package org.jeecg.modules.iot.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author by Administrator
 * @desc:
 * @since 2024-12-09 星期一 10:06:04
 */
@Component
@RequiredArgsConstructor
public class AddressUtil {

    private final RedisTemplate<String, Object> redisTemplate;

    public void addAddressMapping(String deviceId, String seq, int address, long expireSeconds) {
        if (deviceId == null || seq == null || expireSeconds <= 0) {
            // 处理无效参数，例如抛出异常或记录日志
            throw new IllegalArgumentException("Invalid arguments: deviceId, seq, and expireSeconds must be valid.");
        }
        String seqStr = formatSeq(seq);
        String key = "Device:" + deviceId + ":seq:" + seqStr; // 修改键名，使用冒号分隔
        System.out.println("保存的key"+key);
        redisTemplate.opsForValue().set(key, address+"",expireSeconds, TimeUnit.SECONDS);
    }

    public static String formatSeq(String seq) {
        if (seq == null) {
            return "0000"; // 或返回 null，或抛出异常，取决于你的需求
        }

        int len = seq.length();
        if (len < 4) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 4 - len; i++) {
                sb.append('0'); // 补0
            }
            sb.append(seq);
            return sb.toString();
        } else {
            return seq;
        }
    }

    public Integer getAddressAndDelete(String deviceId, String seq) {
        String key = "Device:"+deviceId + ":seq:" + seq ;
        System.out.println("获取的key"+key);
        String addressStr = (String) redisTemplate.opsForValue().get(key);
        if (addressStr != null) {
            redisTemplate.delete(key);
            return Integer.parseInt(addressStr);
        } else {
            return null;
        }
    }
}
